//
//  DDquickViewController.m
//  DingDongZP
//
//  Created by FEIYUE on 16/6/6.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDquickViewController.h"
#import "DDLoginService.h"
#import "DDRegisterSerivce.h"
#import "DDGetVerifyCodeService.h"
#import <AFNetworking/AFNetworking.h>
#import "DDDiscoverViewController.h"


@interface DDquickViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *delu;
@property (weak, nonatomic) IBOutlet UIButton *codeButton;
@property (weak, nonatomic) IBOutlet UIView *accountView;
@property (weak, nonatomic) IBOutlet UIView *codeViews;
@property (weak, nonatomic) IBOutlet UITextField *accountTF;
@property (weak, nonatomic) IBOutlet UITextField *codeTF;
@property (strong, nonatomic) DDLoginService *quickService;
@property (nonatomic) NSTimer *timer;
@property (nonatomic) int countDownTime;
@property (nonatomic)BOOL timeBool;//重新发送后时间到了才允许再次获取

@property (strong, nonatomic) DDRegisterSerivce *registerService;
@property (strong, nonatomic) DDGetVerifyCodeService *getVerifyCodeService;

@end

@implementation DDquickViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.registerService = [[DDRegisterSerivce alloc] init];
        self.getVerifyCodeService = [[DDGetVerifyCodeService alloc] init];
    }
    return self;
}

//倒计时操作
- (void)countDown
{
    self.countDownTime --;
    if (self.countDownTime == 0)
    {
        if ([self.timer isValid]) {
            
            [self.timer invalidate];
            [self changeButtonState];
            return;
        }
    }
    
    [self.codeButton setTitle:[NSString stringWithFormat:@"已发送(%d)",self.countDownTime] forState:UIControlStateNormal];
    [self.codeButton setUserInteractionEnabled:NO];
}

- (void)changeButtonState
{
    [self.codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.codeButton setUserInteractionEnabled:YES];
}

- (void)stopTimer {
    if (nil != self.timer && [self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    if(!self.quickService) {
        self.quickService = [[DDLoginService alloc] init];
    }

    
    self.accountView.layer.masksToBounds = YES;
    self.accountView.layer.cornerRadius = 5.f;
    self.accountTF.keyboardType = UIKeyboardTypePhonePad;
    
    self.codeViews.layer.masksToBounds = YES;
    self.codeViews.layer.cornerRadius = 5.f;
    self.codeTF.keyboardType = UIKeyboardTypePhonePad;
    
    self.delu.layer.cornerRadius = 5.f;
    self.delu.layer.masksToBounds = YES;

    self.accountTF.delegate = self;
    self.codeTF.delegate = self;

}

- (IBAction)mima:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (IBAction)yanzhengma:(id)sender {
    if (![self validatePhoneNumber:self.accountTF.text]) {
        [self showText:@"手机号码格式有误"];
        return;
    }
    [self showLoading];
    WEAKSELF
    [self.getVerifyCodeService queryRegisterWithMobile:self.accountTF.text successBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([weakSelf isValidateResponseData:responseObject]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf showText:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
            });
            
            //获取成功后 倒计时
            weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:weakSelf selector:@selector(countDown) userInfo:nil repeats:YES];
            weakSelf.countDownTime = 60;
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf showText:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
            });
        }
        
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf requestFaild];
    }];
}


- (BOOL)validatePhoneNumber:(NSString *)string
{
    if (string.length != 11) {
        return NO;
    }
    return YES;
}

- (BOOL)validatePassword:(NSString *)password
{
    if (password.length < 6 || password.length > 25) {
        return NO;
    }
    return YES;
}

- (IBAction)dengluClicks:(id)sender {
    
    if (![self validatePhoneNumber:self.accountTF.text]) {
        [self showText:@"手机号码格式有误"];
        return;
    }
    if (self.codeTF.text.length < 1) {
        [self showText:@"验证码格式有误"];
        return;
    }
    
    WEAKSELF
    [weakSelf showLoading];
    if (self.quickService) {
       [self.quickService quickRegisterWithMobile:self.accountTF.text Code:self.codeTF.text successBlock:^(id responseObject) {
           
//           NSLog(@" data == %@",responseObject);
           if ([[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"code"]]isEqualToString:@"0"]) {
               
               [weakSelf showText:[responseObject objectForKey:@"msg"]];
               [weakSelf hideLoading];
           }else if ([[NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"data"]objectForKey:@"is_newUser"]]isEqualToString:@"0"]){
               
               [weakSelf hideLoading];
               UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"您已注册过,请用密码登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
               [alert show];
           }else if ([[NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"data"]objectForKey:@"is_newUser"]]isEqualToString:@"1"]){
               
               [weakSelf hideLoading];

           }
           
       } failBlock:^(id responseObject, NSError *error) {
           
           [weakSelf hideLoading];
           
       }];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (self.view.bounds.origin.y > 190) {
        return;
    }
    CGRect newbounds = self.view.bounds;
    newbounds.origin.y +=190;
    
    [UIView animateWithDuration:.3f animations:^{
        self.view.bounds = newbounds;
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (self.view.bounds.origin.y == 190) {
        CGRect newbounds = self.view.bounds;
        newbounds.origin.y = 0;
        
        [UIView animateWithDuration:.3f animations:^{
            self.view.bounds = newbounds;
        }];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
